﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

public class StickEditor : UnitEditor
{
    public Stick Stick
    {
        get { return SB.Stick; }
        set { SB.Stick = value; }
    }

    public StickBehaviour SB
    {
        get { return UB as StickBehaviour; }
        set { UB = value; }
    }

    protected override void Update()
    {
        var rt = GetComponent<RectTransform>();
        var s = EMgr.View2WorldScale;
        rt.sizeDelta = new Vector2(20, Stick.Length / s + 20);
        transform.localRotation = SB.transform.localRotation;
        base.Update();
    }

    protected override void OnClick(Vector2 pt)
    {
        base.OnClick(pt);
        ShowOpMenu();
    }

    void AdjustAngle()
    {
        var angle = Stick.Angle.RangeInPi();
        if (angle > -Mathf.PI / 4 && angle < Mathf.PI / 4)
            angle = 0;
        else if (angle < -Mathf.PI * 3 / 4 || angle > Mathf.PI * 3 / 4)
            angle = 0;
        else
            angle = Mathf.PI / 2;

        Stick.Angle = angle;
    }

    public override void OnDrag(PointerEventData eventData)
    {
        base.OnDrag(eventData);
        AdjustAngle();
    }

    public override void OnEndDrag(PointerEventData eventData)
    {
        AdjustAngle();
        base.OnEndDrag(eventData);
    }

    void ShowOpMenu()
    {
        var ops = new List<string>();
        ops.Add("X");

        if (Stick.Length < 10)
            ops.Add("+");

        if (Stick.Length > 1)
            ops.Add("-");

        ops.Add("旋转");

        EMgr.ShowOpMenuAt(
            EMgr.World2View(Stick.Pos) + Vector3.up * 
            (Mathf.Abs(Mathf.Cos(Stick.Angle)) * Stick.Length / 2 / EMgr.View2WorldScale + 30),
            new string[][] { ops.ToArray() }, OnOp);
    }

    void OnOp(string op)
    {
        switch (op)
        {
            case "X":
                EMgr.DeleteUnit(this);
                EMgr.CloseOpMenu();
                return;
            case "+":
                Stick.Length++;
                break;
            case "-":
                Stick.Length--;
                break;
            case "旋转":
                Stick.Angle = Stick.Angle == 0 ? Mathf.PI / 2 : 0;
                break;
            default:
                return;
        }

        if (Unit.Src != null)
            Unit.Update(0, Unit.Src.GetLinkType(Unit));
        else
            Unit.UpdateAllChildren(0);

        Refresh();
        ShowOpMenu();
    }
}
